package com.atguigu.tingshu.account.consumer;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 监听充值订单超时未支付消息
 */
@Log4j2
@Component
public class RechargeTimeOutConsumer {
    @Autowired
    private RechargeInfoService rechargeInfoService;

    @SneakyThrows
    @RabbitListener(queues = "account_recharge_delay_queue")
    public void rechargeTimeOut(Channel channel, Message message){
        // 获取信息 -- result = orderNo:userId
        String orderNo = new String(message.getBody());
        // 获取属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 取消充值订单
            System.out.println("尝试删除cancelRechargeInfo " + orderNo);
            rechargeInfoService.cancelRechargeInfo(orderNo);
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            if (messageProperties.getRedelivered()){
                log.error("超时取消订单充值失败, 订单No: " + orderNo + ", 失败原因: " + e.getMessage());
                channel.basicReject(deliveryTag,false);
            }else {
                channel.basicReject(deliveryTag,true);
            }
        }
    }


}
